<template>
  <div class="game-container">
    <!-- 返回按钮 -->
    <button class="back-button" @click="goBack">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="15 18 9 12 15 6"></polyline>
      </svg>
    </button>

    <div class="game-header">
      <div class="score">分数: {{ score }}</div>
      <div class="best-score">最高分: {{ bestScore }}</div>
      <!-- 删除了重新开始按钮 -->
    </div>

    <div class="game-grid">
      <div v-for="(row, rowIndex) in board" :key="rowIndex" class="grid-row">
        <div 
          v-for="(cell, colIndex) in row" 
          :key="colIndex" 
          class="grid-cell"
          :class="[
            'cell-' + cell,
            { 
              merged: mergedCells.some(c => c.row === rowIndex && c.col === colIndex),
              'new-cell': newCells.some(c => c.row === rowIndex && c.col === colIndex)
            }
          ]"
        >
          {{ cell || '' }}
        </div>
      </div>
    </div>

    <!-- 操作提示 -->
    <div class="operation-guide">
      <h3>游戏操作</h3>
        <ul>
        <li>↑ ↓ ← →键: 移动方块</li>
        <li>空格键: 重新开始游戏</li>
      </ul>
    </div>

    <div v-if="gameOver" class="game-over">
      <div class="game-over-content">
        <h2>游戏结束！</h2>
        <p>最终得分: {{ score }}</p>
        <p>历史最高分: {{ bestScore }}</p>
        <!-- 删除了重新开始按钮 -->
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  name: 'Game2048',
  data() {
    return {
      board: Array(4).fill().map(() => Array(4).fill(0)),
      gameOver: false,
      isAnimating: false,
      mergedCells: [],
      newCells: [],
      touchStartX: 0,
      touchStartY: 0,
    }
  },
  computed: {
    ...mapGetters('game2048', ['score', 'bestScore'])
  },
  mounted() {
    // 初始化游戏
    this.initGame()
    // 初始化最高分
    this.initBestScore();
    // 监听键盘事件
    window.addEventListener('keydown', this.handleKeyPress)
    // 添加触摸事件
    this.$el.addEventListener('touchstart', this.handleTouchStart, false);
    this.$el.addEventListener('touchmove', this.handleTouchMove, false);
  },
  unmounted() {
    // 移除键盘事件监听器
    window.removeEventListener('keydown', this.handleKeyPress);
    // 移除触摸事件监听器
    this.$el.removeEventListener('touchstart', this.handleTouchStart, false);
    this.$el.removeEventListener('touchmove', this.handleTouchMove, false);
  },
  methods: { 
    ...mapActions('game2048', ['updateScore', 'resetScore', 'initBestScore']),
    // 添加返回方法
    goBack() {
      this.$router.push('/game');
    },
    // 初始化游戏
    initGame() {
      this.board = Array(4).fill().map(() => Array(4).fill(0))
      this.resetScore();
      this.gameOver = false
      this.generateNewNumber()
      this.generateNewNumber()
    },
    // 生成新的数字
    generateNewNumber() {
      const emptyCells = []
      // 通过遍历获取所有的空的单元格
      this.board.forEach((row, rowIndex) => {
        row.forEach((cell, colIndex) => {
          if (cell === 0) {
            emptyCells.push({ row: rowIndex, col: colIndex })
          }
        })
      })
      // 如果有空的单元格，随机选择一个位置生成新的数字
      if (emptyCells.length > 0) {
        const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)]
        this.board[randomCell.row][randomCell.col] = Math.random() < 0.9 ? 2 : 4
      }
    },
    // 键盘事件处理
    handleKeyPress(event) {
      if (this.gameOver) return
      
      switch(event.key) {
        case ' ':
          // 添加空格键重新开始游戏
          this.resetGame()
          break
        case 'ArrowUp':
          this.moveUp()
          break
        case 'ArrowDown':
          this.moveDown()
          break
        case 'ArrowLeft':
          this.moveLeft()
          break
        case 'ArrowRight':
          this.moveRight()
          break
        default:
          return
      }
    },
    // 移动逻辑
    moveCells(direction) {
      let moved = false;
      if (direction === 'left') {
        for (let i = 0; i < 4; i++) {
          const row = this.board[i].filter(cell => cell !== 0);
          const newRow = [...row, ...Array(4 - row.length).fill(0)];
          
          if (JSON.stringify(newRow) !== JSON.stringify(this.board[i])) {
            moved = true;
            this.board[i] = newRow;
          }
        }
      } else if (direction === 'right') {
        for (let i = 0; i < 4; i++) {
          const row = this.board[i].filter(cell => cell !== 0);
          const newRow = [...Array(4 - row.length).fill(0), ...row];
          
          if (JSON.stringify(newRow) !== JSON.stringify(this.board[i])) {
            moved = true;
            this.board[i] = newRow;
          }
        }
      } else if (direction === 'up') {
        for (let j = 0; j < 4; j++) {
          const column = this.board.map(row => row[j]).filter(cell => cell !== 0);
          const newColumn = [...column, ...Array(4 - column.length).fill(0)];
          
          if (JSON.stringify(newColumn) !== JSON.stringify(this.board.map(row => row[j]))) {
            moved = true;
            for (let i = 0; i < 4; i++) {
              this.board[i][j] = newColumn[i];
            }
          }
        }
      } else if (direction === 'down') {
        for (let j = 0; j < 4; j++) {
          const column = this.board.map(row => row[j]).filter(cell => cell !== 0);
          const newColumn = [...Array(4 - column.length).fill(0), ...column];
          
          if (JSON.stringify(newColumn) !== JSON.stringify(this.board.map(row => row[j]))) {
            moved = true;
            for (let i = 0; i < 4; i++) {
              this.board[i][j] = newColumn[i];
            }
          }
        }
      }
      return moved;
    },
    // 向左移动
    async moveLeft() {
      if (this.isAnimating) return;
      this.isAnimating = true;
      // 保存移动前的棋盘状态
      const previousBoard = JSON.stringify(this.board);
      const moved = this.moveCells('left');
      const rowsToMerge = this.board.map(row => row.filter(cell => cell !== 0));
      const mergedRows = rowsToMerge.map(row => this.mergeRow(row));
      
      // 直接更新面板
      this.board = mergedRows.map(mergedRow => 
        [...mergedRow, ...Array(4 - mergedRow.length).fill(0)]
      );
      
      // 触发合并动画
      this.mergedCells = mergedRows.flatMap((row, i) => 
        row.map((_, j) => ({ row: i, col: j }))
      );
      // 检查移动或合并后的棋盘状态是否发生变化
      const boardChanged = moved || previousBoard !== JSON.stringify(this.board);
      if (boardChanged) {
        // 生成新数字并触发生成动画
        this.$nextTick(() => {
          this.generateNewNumber();
          this.newCells = this.getNewCells();
        });
      }
      
      this.mergedCells = [];
      this.isAnimating = false;
      this.checkGameOver();
    },
    async moveRight() {
      if (this.isAnimating) return;
      this.isAnimating = true;
      // 保存移动前的棋盘状态
      const previousBoard = JSON.stringify(this.board);

      const moved = this.moveCells('right');
      const rowsToMerge = this.board.map(row => [...row].reverse().filter(cell => cell !== 0));
      const mergedRows = rowsToMerge.map(row => this.mergeRow(row));
      
      this.board = mergedRows.map(mergedRow => 
        [...Array(4 - mergedRow.length).fill(0), ...mergedRow.reverse()]
      );
      
      this.mergedCells = mergedRows.flatMap((row, i) => 
        row.map((_, j) => ({ row: i, col: 3 - j }))
      );

      // 检查移动或合并后的棋盘状态是否发生变化
      const boardChanged = moved || previousBoard !== JSON.stringify(this.board);
      if (boardChanged) {
        // 生成新数字并触发生成动画
        this.$nextTick(() => {
          this.generateNewNumber();
          this.newCells = this.getNewCells();
        });
      }
      
      this.mergedCells = [];
      this.isAnimating = false;
      this.checkGameOver();
    },
     // 向上移动
    async moveUp() {
      if (this.isAnimating) return;
      this.isAnimating = true;
      const moved = this.moveCells('up');
      // 保存移动前的棋盘状态
      const previousBoard = JSON.stringify(this.board);
      const columnsToMerge = Array(4).fill().map((_, j) => 
        this.board.map(row => row[j]).filter(cell => cell !== 0)
      );
      const mergedColumns = columnsToMerge.map(col => this.mergeRow(col));
      
      mergedColumns.forEach((col, j) => {
        for (let i = 0; i < 4; i++) {
          this.board[i][j] = i < col.length ? col[i] : 0;
        }
      });
      
      this.mergedCells = mergedColumns.flatMap((col, j) => 
        col.map((_, i) => ({ row: i, col: j }))
      );      
      // 检查移动或合并后的棋盘状态是否发生变化
      const boardChanged = moved || previousBoard !== JSON.stringify(this.board);
      if (boardChanged) {
        // 生成新数字并触发生成动画
        this.$nextTick(() => {
          this.generateNewNumber();
          this.newCells = this.getNewCells();
        });
      }
      
      this.mergedCells = [];
      this.isAnimating = false;
      this.checkGameOver();
    },
    // 向下移动
    async moveDown() {
      if (this.isAnimating) return;
      this.isAnimating = true;
      const moved = this.moveCells('down');
      // 保存移动前的棋盘状态
      const previousBoard = JSON.stringify(this.board);
      const columnsToMerge = Array(4).fill().map((_, j) => 
        this.board.map(row => row[j]).reverse().filter(cell => cell !== 0)
      );
      const mergedColumns = columnsToMerge.map(col => this.mergeRow(col));
      
      mergedColumns.forEach((col, j) => {
        for (let i = 0; i < 4; i++) {
          this.board[3 - i][j] = i < col.length ? col[i] : 0;
        }
      });
      
      this.mergedCells = mergedColumns.flatMap((col, j) => 
        col.map((_, i) => ({ row: 3 - i, col: j }))
      );
      // 检查移动或合并后的棋盘状态是否发生变化
      const boardChanged = moved || previousBoard !== JSON.stringify(this.board);
      
      if (boardChanged) {
        // 生成新数字并触发生成动画
        this.$nextTick(() => {
          this.generateNewNumber();
          this.newCells = this.getNewCells();
        });
      }
      this.mergedCells = [];
      this.isAnimating = false;
      this.checkGameOver();
    },
    // 添加新方法
    getNewCells() {
      const newCells = [];
      this.board.forEach((row, i) => {
        row.forEach((cell, j) => {
          if (cell === 2 || cell === 4) {
            newCells.push({ row: i, col: j });
          }
        });
      });
      return newCells;
    },
    // 合并行
    mergeRow(row) {
      const merged = [];
      for (let i = 0; i < row.length; i++) {
        if (i < row.length - 1 && row[i] === row[i + 1]) {
          merged.push(row[i] * 2);
          // 更新得分
          this.updateScore(this.score + row[i] * 2);
          i++;
        } else {
          merged.push(row[i]);
        }
      }
      return merged;
    },
    // 检查游戏是否结束
    checkGameOver() {
      // 检查是否还有空格
      for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
          if (this.board[i][j] === 0) return false;
        }
      }
      
      // 检查是否还能合并
      for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 3; j++) {
          if (this.board[i][j] === this.board[i][j + 1]) return false;
        }
      }
      for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 4; j++) {
          if (this.board[i][j] === this.board[i + 1][j]) return false;
        }
      }
      
      this.gameOver = true;
      return true;
    },
    // 重新开始
    resetGame() {
      this.initGame()
    },
    // 触摸事件处理
    handleTouchStart(e) {
      this.touchStartX = e.touches[0].clientX;
      this.touchStartY = e.touches[0].clientY;
    },
    // 触摸移动
    handleTouchMove(e) {
      if (!this.touchStartX || !this.touchStartY) return;
      
      const touchEndX = e.touches[0].clientX;
      const touchEndY = e.touches[0].clientY;
      const diffX = this.touchStartX - touchEndX;
      const diffY = this.touchStartY - touchEndY;
      
      // 确定滑动方向
      if (Math.abs(diffX) > Math.abs(diffY)) {
        // 水平滑动
        if (diffX > 0) {
          this.moveLeft(); // 向左滑动
        } else {
          this.moveRight(); // 向右滑动
        }
      } else {
        // 垂直滑动
        if (diffY > 0) {
          this.moveUp(); // 向上滑动
        } else {
          this.moveDown(); // 向下滑动
        }
      }
      
      // 重置起始位置
      this.touchStartX = 0;
      this.touchStartY = 0;
      e.preventDefault();
    },
  }
}
</script>

<style scoped>
.game-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #272626;
  position: relative;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  z-index: 100;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(0, 0, 0, 0.8);
  transform: scale(1.05);
}

.game-header {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 450px;
  margin-bottom: 20px;
  color: white;
}

.score, .best-score {
  font-size: 18px;
  font-weight: bold;
}

.game-grid {
  background: #bbada0;
  padding: 15px;
  border-radius: 6px;
}

.grid-row {
  display: flex;
}

.grid-cell {
  width: 100px;
  height: 100px;
  margin: 5px;
  background: rgba(238, 228, 218, 0.35);
  border-radius: 3px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  color: #776e65;
}

.cell-2 { background: #eee4da; }
.cell-4 { background: #ede0c8; }
.cell-8 { background: #f2b179; color: #f9f6f2; }
.cell-16 { background: #f59563; color: #f9f6f2; }
.cell-32 { background: #f67c5f; color: #f9f6f2; }
.cell-64 { background: #f65e3b; color: #f9f6f2; }
.cell-128 { background: #edcf72; color: #f9f6f2; }
.cell-256 { background: #edcc61; color: #f9f6f2; }
.cell-512 { background: #edc850; color: #f9f6f2; }
.cell-1024 { background: #edc53f; color: #f9f6f2; }
.cell-2048 { background: #edc22e; color: #f9f6f2; }
.cell {}

.merged {
  animation: mergeEffect 0.2s ease;
}

@keyframes mergeEffect {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}
/* 添加生成动画 */
.new-cell {
  animation: generateEffect 0.3s ease;
}

@keyframes generateEffect {
  0% { transform: scale(0); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}

/* 操作指南样式 */
.operation-guide {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px;
  border-radius: 10px;
  max-width: 200px;
  z-index: 100;
}

.operation-guide h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 5px;
}

.operation-guide ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.operation-guide li {
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 游戏结束样式 */
.game-over {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}

.game-over-content {
  text-align: center;
  color: white;
  background: rgba(0, 0, 0, 0.8);
  padding: 30px;
  border-radius: 10px;
}

.game-over-content h2 {
  font-size: 36px;
  margin-bottom: 15px;
}

.game-over-content p {
  font-size: 18px;
  margin-bottom: 20px;
}
</style>